import {
    CrsClient
} from "./crsClient";
import {
    CryptoJS
} from "./CryptoJS";


function rpx(n, sizeType) {
    if (sizeType === 'save') {
        return n
    } else {
        return n * system.windowWidth / 750
    }
}

import * as THREE from '../../libs/threejs/three.min'
import {
    initScene,
    hideModel,
    showModel,
    // remove
} from './service'

const systemInfo = wx.getSystemInfoSync();

const SELECT_TYPE = {
    NONE: 0,
    IMAGE: 1,
    VIDEO: 2,
};

const app = getApp()
const avatarSound = app.globalData.innerAudioContext

Page({
    data: {
        // showOverlay: true,
        // showSelect: false,
        // SELECT_TYPE: SELECT_TYPE,
        // selectType: 0,
        // canvasW: width * 0.8, //画布宽度
        canvasType: false,


        //CRS配置
        config: {
            apiKey: '70cf9cf83853d75efdf623f29d3e7034', // EasyAR开发中心 - API KEY - API Key
            apiSecret: '33a5ea2f2a44d533214cfeaf3f4362ff6ad61c4b18097beef7203603a4228f2d', // EasyAR开发中心 - API KEY - API Secret
            crsAppId: '9ae112036a4065166e7414b1a5ae8fdf', // EasyAR开发中心 - 云服务 - 云识别管理 - 云识别库信息 - CRS AppId
            token: '',
            clientHost: 'https://cn1-crs.easyar.com:8443', //服务器一般不变
            jpegQuality: 0.7, //JPEG压缩质量，建议不低于70%
            minInterval: 1000, //最短的两次CRS请求间隔
        },
        //识别到这个数组中的ID就触发内容
        targetIds: [
            // "TODO 云识别管理 - 某个图库 - 识别图 - 某个识别图的ID",
            // "9785213a-f1ac-4a2b-9cdc-c866ce3bec91"
            {
                id: "5bc5a0fe-3edc-48df-aa9e-a2d14dd60314",
                img: '/images/point/point_cont_3.png'
            }
        ],

        showLoading: false,
        showLoadingText: "",
        status: 2,
        id: "",
        showResult: false,
        canvasId: "",
        showText: false,
        showCarama: false,
        showModel: true,
        currentImg: ''
    },

    /** @type {CameraFrameListener} 相机帧回调 */
    listener: undefined,
    /** @type {HTMLCanvasElement} canvas对象 */
    canvas: undefined,

    /** @type {boolean} 是否需要持续识别，在点击“识别体验”之后和识别成功之前为true */
    runningCrs: undefined,
    /** @type {boolean} 当前是否正在进行CRS请求 */
    busy: undefined,
    /** @type {CrsClient} 负责发起CRS请求的对象 */
    crsClient: undefined,
    /** @type {number} 最后一次CRS请求的事件，用于判断是否满足最短请求间隔 */
    last: undefined,

    onLoad: function (options) {
        let self = this;
        let id = options.id;
        let type = options.type;
        console.log(type, "类型")
        // self.scan()
        setTimeout(function () {
            self.setData({
                id: id,
                type: type,
                showLoading: false,
                showResult: true
            })

            // 3d模型加载，语音讲解
            wx.createSelectorQuery().select('#mainCanvas').node().exec((res) => {
                const canvas = THREE.global.registerCanvas(res[0].node)
                console.log(canvas._canvasId, "绘图id")
                self.setData({
                    canvasId: canvas._canvasId
                })
                initScene(canvas, type)

            })
        }, 5000)

    },
    onUnload() {
        console.log(this.data.canvasId, "销毁")
        if (this.data.canvasId) {
            THREE.global.unregisterCanvas(this.data.canvasId)
        }
        // remove()

        avatarSound.src = ''
        avatarSound.stop()
        // removeModel()
        // clearScene()
    },
    onReady: function () {
        if (systemInfo.platform === "devtools") { //开发工具不会触发initdone事件，于是在onReady手动触发
            this.onCameraInit();
        }

        // 获取token
        this.queryToken().then(msg => {
            this.data.config.token = msg.result.token;
        }).catch(err => {
            console.info(err);
        });
    },

    openText() {
        console.log(111)
        hideModel()
        this.setData({
            showText: true,
        })

    },

    hideText() {
        showModel()
        this.setData({
            showText: false,
        })
    },


    openCarama() {
        hideModel()
        this.setData({
            showCarama: true
        }, function () {
            // this.drawImage()
        })
    },

    hideCarama() {
        this.setData({
            showCarama: false
        })
    },

    back() {
        wx.reLaunch({
            url: '/pages/home/home',
        })
    },

    drawImage(path) {
        let self = this;
        wx.createSelectorQuery()
            .select('#myCanvas') // 在 WXML 中填入的 id
            .fields({
                node: true,
                size: true
            })
            .exec((res) => {
                // Canvas 对象
                const canvas = res[0].node
                // 渲染上下文
                const ctx = canvas.getContext('2d')
                const dpr = wx.getSystemInfoSync().pixelRatio
                canvas.width = res[0].width * dpr
                canvas.height = res[0].height * dpr
                console.log(canvas.height*0.8, canvas.width, dpr, "高度")
                // ctx.scale(1, 1.5)
                const image1 = canvas.createImage()
                // 设置图片src
                console.log(this.data.type, "保存时候类型")

                image1.src = path
                image1.onload = () => {
                    // 将图片绘制到 canvas 上
                    ctx.drawImage(image1, 0, 0, 600, 700)
                }

                const image3 = canvas.createImage()
                

                image3.src = 'https://txcy.oss-cn-hangzhou.aliyuncs.com/bg_2.png'
                image3.onload = () => {
                    // 将图片绘制到 canvas 上
                    ctx.drawImage(image3, 0, 230, 600, 470)
                }

                const image2 = canvas.createImage()
                image2.src = "../../images/dao/code.png"
                image2.onload = () => {
                    // 将图片绘制到 canvas 上
                    ctx.drawImage(image2, canvas.width-100, 750, 80, 80)
                }
                ctx.font = "28px Georgia"
                ctx.fillText('金龙港', 20, 780)
                ctx.fillText('五三路口', 20, 820)




                self.setData({
                    canvas: canvas
                })
            })
    },

    reactImg(){
        console.log(11)
        wx.onUserCaptureScreen(function (res) {
            console.log(res,'用户截屏了')
          })
    },
    

    takePhoto() {
        let self = this;
        hideModel()//隐藏模型
        self.setData({
            showCarama: true
        }, function () {
            const ctx = wx.createCameraContext()
            ctx.takePhoto({
                quality: 'normal', //high normal low
                success: (res) => {
                    console.log(res, "拍照")
                    let path = res.tempImagePath
                    self.drawImage(path)
                    // this.setData({
                    //     src: res.tempImagePath
                    // })
                }
            })
        })

    },

    save() {
        var _this = this;
        // wx.canvasToTempFilePath({
        //   // 把画布转化成临时文件
        //   x: 0,
        //   y: 0,
        //   width: 600, // 截取的画布的宽
        //   height: 800, // 截取的画布的高
        //   destWidth: 600, // 保存成的画布宽度
        //   destHeight: 800, // 保存成的画布高度
        //   fileType: 'jpg', // 保存成的文件类型
        //   quality: 1, // 图片质量
        //   canvas: _this.data.canvas, // 画布ID
        //   success(res) {
        //     console.log(res,"临时图片")
        //     _this.setData({
        //       picTempUrl:res.tempFilePath
        //     })
        //     // 2-保存图片至相册

        //   },
        //   fail() {
        //     wx.showToast({
        //       title: '保存失败，稍后再试',
        //       duration: 2000,
        //       icon: 'none'
        //     });
        //     wx.hideLoading();
        //   }
        // });
        let path = ""
        if (this.data.type == 2) {
            path = '/images/result/result_2.png'
        } else {
            path = '/images/scan/canvas_1.png'
        }
        wx.saveImageToPhotosAlbum({
            // 存成图片至手机
            filePath: path,
            success(res2) {
                wx.hideLoading();
                wx.showToast({
                    title: '保存成功',
                    duration: 2000
                });
            },
            fail(res3) {
                if (res3.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                    wx.showToast({
                        title: '保存失败，稍后再试',
                        duration: 2000,
                        icon: 'none'
                    });
                    wx.hideLoading();
                } else {
                    wx.showToast({
                        title: '保存失败，稍后再试',
                        duration: 2000,
                        icon: 'none'
                    });
                    wx.hideLoading();
                }
            }
        });
    },

    downLoadImg() {
        // if(!this.data.imgUrl){
        //   console.log('图片获取失败，请稍后再试')
        //   return;
        // }
        let path = ""
        if (this.data.type == 2) {
            path = 'https://txcy.oss-cn-hangzhou.aliyuncs.com/result_2.png'
        } else {
            path = 'https://txcy.oss-cn-hangzhou.aliyuncs.com/canvas_2.png'
        }
        wx.showLoading({
            title: '加载中...',
        })
        //图片保存到本地
        wx.downloadFile({
            url: path, //图片地址
            success(downres) {
                // 保存图片到相册
                wx.saveImageToPhotosAlbum({
                    filePath: downres.tempFilePath,
                    success(res) {
                        wx.hideLoading()
                        console.log('保存成功')
                    },
                    fail(err) {
                        wx.hideLoading()
                        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                            // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                            wx.showModal({
                                title: '提示',
                                content: '请授权保存到相册',
                                showCancel: false,
                                success() {
                                    wx.openSetting({
                                        success(openres) {
                                            console.log("openres", openres)
                                            if (openres.authSetting['scope.writePhotosAlbum']) {
                                                console.log('获取权限成功，再次点击图片即可保存')
                                            } else {
                                                console.log('获取权限失败，无法保存到相册哦~')
                                            }
                                        },
                                        fail(failerr) {
                                            console.log("failerr", failerr)
                                        }
                                    })
                                }
                            })
                        }
                    }
                })
            },
            fail() {
                wx.hideLoading()
                console.log('下载失败，请稍后再试')
            }
        })
    },

    saveImg() {
        let that = this;
        //文件名设置为时间戳
        let fileName = new Date().valueOf();

        let path = ""
        if (this.data.type == 2) {
            path = 'https://txcy.oss-cn-hangzhou.aliyuncs.com/result_2.png'
        } else {
            path = 'https://txcy.oss-cn-hangzhou.aliyuncs.com/canvas_2.png'
        }

        wx.downloadFile({ //下载图片到本地
            url: path,
            // filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.png',
            success(res) {
                console.log(res, "下载网络图片到本地")
                if (res.statusCode === 200) {
                    debugger
                    let img = res.filePath
                    wx.saveImageToPhotosAlbum({ //只支持本地图片所以要先把图片下载下来
                        filePath: img,
                        success(result) {
                            console.log(result)
                            wx.showToast({
                                title: '已保存至相册',
                                icon: "none",
                            })
                        },
                        fail(res) {
                            console.log(result)
                            wx.showToast({
                                title: '保存失败',
                                icon: "none",
                            })
                        }
                    })
                }
            }
        })
    },




    showLoading(text) {
        this.setData({
            showLoading: true,
            showLoadingText: text,
        });
    },
    hideLoading() {
        this.setData({
            showLoading: false,
        });
    },

    //图像识别部分：

    onShow: function () {
        if (this.listener) this.listener.start(); //页面隐藏时相机帧的监听会自动停止，但恢复展示时不会自动启动，这里手动启动
    },

    onCameraInit: function () {
        //找到canvas对象
        const query = wx.createSelectorQuery();
        query.select('#capture')
            .fields({
                node: true
            })
            .exec((res) => {
                const canvas = res[0].node;
                //设置canvas内部尺寸为480*640，frame-size="medium"的设置下相机帧大多是480*640
                canvas.width = 480;
                canvas.height = 640;
                this.canvas = canvas;

                this.crsClient = new CrsClient(this.data.config, this.canvas);

                //开始监听相机帧
                let cameraContext = wx.createCameraContext();
                this.listener = cameraContext.onCameraFrame(frame => {
                    if (!this.canvas) return;
                    let canvas = this.canvas;
                    //如果尺寸不匹配，就修改canvas尺寸以适应相机帧
                    if (canvas.width !== frame.width || canvas.height !== frame.height) {
                        canvas.width = frame.width;
                        canvas.height = frame.height;
                    }

                    this.queryImage(frame);
                });
                this.listener.start();
            });
    },

    queryImage: function (frame) {
        if (!this.runningCrs || this.busy || !this.crsClient) return;

        //最短的两次CRS请求间隔
        let now = new Date().getTime();
        if (this.last && (now - this.last < this.data.config.minInterval)) return;
        this.last = now;

        this.busy = true; //如果正在进行CRS请求，就不允许再次请求

        this.crsClient.queryImage(frame).then(res => {
            if (!this.runningCrs) return; //避免在停止后仍然触发
            let result = res && res.result;
            console.log("返回结果", result)
            if (!result) return;

            if (result.target) {

                console.log("识别成功", result.target.targetId);
                this.runningCrs = false;
                this.hideLoading();
                // todo: 解析meta中的信息，触发业务逻辑

                //如果待触发的id列表中存在识别到的这个id，就触发
                // if (this.data.targetIds.find(targetId => targetId === result.target.targetId)) {
                //     this.onResult(result.target);
                // }

                if (this.data.targetIds.find(item => item.id === result.target.targetId)) {
                    // this.onResult(result.target);
                    let index = this.data.targetIds.findIndex(item => item.id == result.target.targetId)
                    console.log("图片url:", index)
                    this.setData({
                        showResult: true,
                        currentImg: this.data.targetIds[index]['img']
                    })
                }

                // 3d模型加载，语音讲解
                // wx.createSelectorQuery().select('#mainCanvas').node().exec((res) => {
                //     const canvas = THREE.global.registerCanvas(res[0].node)
                //     self.setData({
                //       canvasId: canvas._canvasId
                //     })
                //     initScene(canvas, type)
                //   })
            } else {
                console.log("识别失败", result.message);
            }
            this.busy = false;
        }).catch(e => {
            this.busy = false;
            console.log(e);
        }); //小程序iOS端不支持finally，所以在then和catch里分别设置busy = false
    },

    // onResult: function (target) {
    //     console.log("触发内容!");
    //     if (target.meta) {
    //         console.log("meta base64:", target.meta);
    //     }
    //     this.setData({
    //         showOverlay: false,
    //         showContent: true,
    //         selectType: SELECT_TYPE.IMAGE,
    //     });
    // },

    //界面：

    // back: function () {
    //     this.runningCrs = false;
    //     this.setData({
    //         showOverlay: true,
    //         showContent: false,
    //         selectType: SELECT_TYPE.NONE,
    //     });
    //     this.hideLoading();
    // },

    // experience: function () {
    //     this.setData({
    //         showOverlay: false,
    //         showContent: true,
    //         selectType: SELECT_TYPE.IMAGE,
    //     });
    // },



    scan: function () {
        this.runningCrs = true;
        this.setData({
            // showOverlay: false,
            // showContent: false,
            // selectType: SELECT_TYPE.NONE,
            runningCrs: true
        });
        this.showLoading("识别中");
    },

    download: function () {
        wx.saveImageToPhotosAlbum({
            filePath: "/images/namecard.jpg",
            success: res => {
                wx.showToast({
                    title: "已保存到相册",
                    icon: "none"
                });
            },
            fail: res => {
                wx.showToast({
                    title: "保存失败",
                    icon: "none"
                });
            },
        });
    },

    selectContent: function (e) {
        this.setData({
            selectType: e.currentTarget.dataset.contenttype,
        });
    },

    /**
     * 生成token
     */
    queryToken: function () {
        const obj = {
            'apiKey': this.data.config.apiKey,
            'expires': 86400,
            'timestamp': Date.now(),
            'acl': `[{"service":"ecs:crs","effect":"Allow","resource":["${this.data.config.crsAppId}"],"permission":["READ","WRITE"]}]`
        };

        const str = Object.keys(obj).sort().map(k => k + obj[k]).join('');
        obj.signature = CryptoJS.SHA256(str + this.data.config.apiSecret, '').toString();

        return new Promise((resolve, reject) => {
            wx.request({
                url: 'https://uac.easyar.com/token/v2',
                method: 'post',
                data: obj,
                header: {
                    'content-type': 'application/json'
                },
                success: res => resolve(res.data),
                fail: err => reject(err),
            });
        });
    },
});